<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>API调用</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="$router.go(-1)">返回</el-button>
      </div>
      
      <!-- API基本信息 -->
      <div class="api-info" v-loading="loading">
        <h2>{{ apiInfo.name }}</h2>
        <p class="description">{{ apiInfo.description }}</p>
        <div class="meta-info">
          <el-tag size="small">{{ apiInfo.method }}</el-tag>
          <span class="url">{{ apiInfo.url }}</span>
        </div>
      </div>

      <!-- 请求参数 -->
      <div class="section">
        <h3>请求参数</h3>
        <el-table :data="apiInfo.requestParams" border style="width: 100%">
          <el-table-column prop="name" label="参数名" width="120" />
          <el-table-column label="传递参数" width="180">
            <template slot-scope="scope">
              <div>
                <div>示例值：{{ scope.row.param }}</div>
                <div v-if="scope.row.enum && scope.row.enum.length">
                  <small>可选值：{{ scope.row.enum.join(' | ') }}</small>
                </div>
                <div v-if="scope.row.default">
                  <small>默认值：{{ scope.row.default }}</small>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="position" label="传入位置" width="100">
            <template slot-scope="scope">
              <el-tag size="small" :type="getPositionType(scope.row.position)">
                {{ scope.row.position }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" width="100" />
          <el-table-column prop="description" label="参数说明" show-overflow-tooltip />
          <el-table-column label="是否必需" width="80" align="center">
            <template slot-scope="scope">
              <el-tag size="small" :type="scope.row.required ? 'danger' : 'info'">
                {{ scope.row.required ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 参数输入表单 -->
      <div class="section" v-if="apiInfo.requestParams && apiInfo.requestParams.length > 0">
        <h3>参数输入</h3>
        <el-form ref="form" :model="form" label-width="120px">
          <el-form-item v-for="param in apiInfo.requestParams" 
            :key="param.name" 
            :label="param.name"
            :required="param.required">
            <el-input v-model="form[param.name]" :placeholder="param.description"></el-input>
          </el-form-item>
        </el-form>
      </div>

      <!-- 调用按钮 -->
      <div class="action-bar">
        <el-button type="primary" @click="handleCall" :loading="calling">
          发送请求
        </el-button>
      </div>

      <!-- 响应结果 -->
      <div class="section" v-if="response">
        <h3>响应结果</h3>
        <div v-if="isImageResponse" class="image-response">
          <div class="image-preview">
            <img 
              :src="extractedImageUrl" 
              alt="API返回图片" 
              @error="handleImageError" 
              v-if="!imageLoadError"
              @click="previewImage"
              class="preview-image"
            />
            <div v-else class="image-error">
              <i class="el-icon-picture-outline"></i>
              <p>图片加载失败</p>
              <el-button size="small" type="primary" plain @click="reloadImage">重试</el-button>
            </div>
          </div>
          <div class="response-actions">
            <el-button size="small" type="text" @click="showOriginalResponse = !showOriginalResponse">
              {{ showOriginalResponse ? '隐藏' : '查看' }}原始响应
            </el-button>
          </div>
          <pre v-if="showOriginalResponse" class="response-box response-original">{{ response }}</pre>
        </div>
        <pre v-else class="response-box">{{ formatResponse }}</pre>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getApiDetail, callApi } from '@/api/front'

export default {
  name: 'ApiCall',
  data() {
    return {
      loading: false,
      calling: false,
      apiInfo: {},
      form: {},
      response: null,
      showOriginalResponse: false,
      imageLoadError: false
    }
  },
  computed: {
    formatResponse() {
      return JSON.stringify(this.response, null, 2)
    },
    isImageResponse() {
      // 检测响应是否为HTML图片链接格式
      if (typeof this.response === 'string') {
        // 检查是否包含图片链接的HTML标签
        return this.response.includes('<a href=') && 
               (this.response.includes('.jpg') || 
                this.response.includes('.png') || 
                this.response.includes('.gif') || 
                this.response.includes('.webp')) && 
               this.response.includes('>Found</a>');
      }
      return false;
    },
    extractedImageUrl() {
      // 提取图片URL
      if (!this.isImageResponse || typeof this.response !== 'string') {
        return '';
      }
      
      // 尝试多种方式提取URL
      // 1. 标准href属性
      let matches = this.response.match(/href="([^"]+)"/);
      if (matches && matches.length > 1) {
        return matches[1];
      }
      
      // 2. 单引号href
      matches = this.response.match(/href='([^']+)'/);
      if (matches && matches.length > 1) {
        return matches[1];
      }
      
      // 3. 直接匹配URL
      matches = this.response.match(/(https?:\/\/[^\s"'<>]+\.(jpg|jpeg|png|gif|webp))/i);
      if (matches && matches.length > 0) {
        return matches[0];
      }
      
      return '';
    }
  },
  created() {
    this.getApiInfo()
  },
  methods: {
    getApiInfo() {
      this.loading = true
      const id = this.$route.params.id
      getApiDetail(id).then(response => {
        if (!response.data) {
          throw new Error('API数据为空')
        }
        
        // 处理API基本信息
        this.apiInfo = {
          ...response.data,
          requestParams: []
        }
        
        // 处理请求参数
        if (response.data.requestParams) {
          try {
            let requestData = response.data.requestParams
            // 如果是字符串，尝试解析JSON
            if (typeof requestData === 'string') {
              requestData = JSON.parse(requestData)
            }
            
            // 从params数组中获取参数信息
            if (requestData.params && Array.isArray(requestData.params)) {
              this.apiInfo.requestParams = requestData.params.map(param => ({
                name: param.name || '',                    // 参数名
                param: param.example || param.default || '', // 传递参数（使用示例值或默认值）
                position: param.location || 'query',       // 传入位置
                type: param.type || 'string',             // 类型
                description: param.description || '',      // 参数说明
                required: param.required || false,         // 是否必需
                enum: param.enum || [],                   // 可选值
                default: param.default || ''              // 默认值
              }))
            }
            
            // 初始化表单
            this.apiInfo.requestParams.forEach(param => {
              this.$set(this.form, param.name, param.default || '')
            })
            
            console.log('处理后的请求参数:', this.apiInfo.requestParams)
          } catch (e) {
            console.error('解析请求参数失败:', e)
            this.$message.error('解析请求参数失败')
          }
        }
        this.loading = false
      }).catch(error => {
        console.error('获取API信息失败:', error)
        this.loading = false
        this.$message.error(error.message || '获取API信息失败')
      })
    },
    handleCall() {
      this.calling = true;
      this.response = null;
      this.imageLoadError = false; // 重置图片错误状态
      
      // 获取用户ID
      const userId = this.$store.state.user.id;
      if (!userId) {
        this.$message.error('请先登录');
        this.calling = false;
        return;
      }
      
      // 构造符合后端要求的请求参数
      const requestData = {
        apiId: this.$route.params.id,
        userId: userId,
        params: this.form
      };
      
      callApi(requestData).then(response => {
        this.response = response.data;
        this.$message.success('调用成功');
      }).catch(error => {
        this.response = error.response?.data || { error: '调用失败' };
        this.$message.error(error.response?.data?.msg || '调用失败');
      }).finally(() => {
        this.calling = false;
      });
    },
    getPositionType(position) {
      const types = {
        'header': 'warning',
        'query': 'success',
        'body': 'primary',
        'path': 'danger'
      }
      return types[position] || 'info'
    },
    handleImageError() {
      this.imageLoadError = true;
      console.error('图片加载失败:', this.extractedImageUrl);
    },
    
    reloadImage() {
      this.imageLoadError = false;
    },
    
    previewImage() {
      if (!this.extractedImageUrl) return;
      
      // 使用Element UI的图片预览组件
      const h = this.$createElement;
      this.$msgbox({
        title: '图片预览',
        message: h('div', { class: 'fullscreen-preview' }, [
          h('img', {
            attrs: { src: this.extractedImageUrl, alt: 'API返回图片' },
            style: { maxWidth: '100%', maxHeight: '80vh' }
          })
        ]),
        showCancelButton: false,
        confirmButtonText: '关闭',
        customClass: 'image-preview-dialog'
      }).catch(() => {});
    },
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;

  .api-info {
    margin-bottom: 24px;

    h2 {
      margin: 0 0 12px;
      font-size: 24px;
      color: #303133;
    }

    .description {
      color: #606266;
      margin-bottom: 16px;
    }

    .meta-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .url {
        color: #409EFF;
        font-family: monospace;
      }
    }
  }

  .section {
    margin-top: 24px;

    h3 {
      margin: 0 0 16px;
      font-size: 18px;
      color: #303133;
    }
  }

  .action-bar {
    margin: 24px 0;
    text-align: center;
  }

  .response-box {
    background: #f5f7fa;
    padding: 16px;
    border-radius: 4px;
    font-family: monospace;
    white-space: pre-wrap;
    word-wrap: break-word;
  }

  .image-response {
    padding: 16px;
    border-radius: 4px;
    background: #f5f7fa;
    margin-bottom: 24px;
  }

  .image-preview {
    margin-top: 16px;
    text-align: center;
    
    img {
      max-width: 100%;
      max-height: 600px;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      
      &.preview-image {
        cursor: pointer;
        transition: transform 0.3s;
        
        &:hover {
          transform: scale(1.02);
        }
      }
    }
  }

  .response-actions {
    margin-top: 16px;
    text-align: right;
  }
  
  .response-original {
    margin-top: 16px;
    border-top: 1px dashed #dcdfe6;
    padding-top: 16px;
    font-size: 12px;
    opacity: 0.8;
  }

  .image-error {
    text-align: center;
    padding: 16px;
    border-radius: 4px;
    background: #f5f7fa;
    margin-top: 16px;

    i {
      font-size: 24px;
      color: #606266;
      margin-bottom: 8px;
    }

    p {
      color: #606266;
      margin: 0;
    }
  }
}
</style>

<style>
/* 全局样式，不使用scoped */
.image-preview-dialog {
  width: auto;
  max-width: 90vw;
}

.image-preview-dialog .el-message-box__message {
  text-align: center;
  margin: 0;
  padding: 0;
}

.image-preview-dialog .el-message-box__header {
  padding: 10px;
}

.image-preview-dialog .el-message-box__content {
  padding: 10px;
}

.fullscreen-preview {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style> 